package com.microDynamic.service.biz;

import com.microDynamic.entity.testCasePo.TestMeterSphereCasePo;
import com.microDynamic.entity.testCasePo.TestOnesCasePo;
import com.microDynamic.utils.FileExtension;
import com.microDynamic.utils.FileUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * &Desc XMind to Excel tool
 */
@Component
public class XMindToExcel {
    private static Logger logger = LoggerFactory.getLogger(XMindToExcel.class);

    /** XMind 原始文件 */
    //static File xMindFile;

    /** MS用例集合 */
    //static List<TestMeterSphereCasePo> testCases = new ArrayList<>();

    /** ones用例集合 */
    //static List<TestOnesCasePo> testOnesCases = new ArrayList<>();

    /** 用例集合 */
    //public static TestCaseInfoPo testCaseInfo = new TestCaseInfoPo();

    /***
     * &Desc: 解析XMind: 根节点的信息
     * @param node 指定节点开始解析
     * @return void
     */
    public static void dealXMindRootInfo(Element node){
        // 获取root topic信息
        if("sheet".equals(node.getName())){
            logger.info("###########解析 root topic 信息###########");
            Element firstElement = node.element("topic");
            Element firstTopicNotes = firstElement.element("notes");
            if(firstTopicNotes !=  null){
                Element html = firstTopicNotes.element("html");
                List<Element> topicNotesProperty = html.elements();
                logger.info("###########开始获取root topic备注信息###########");
                for (Element e: topicNotesProperty) {
                    logger.info("=====================>" + e.getStringValue());
                }
                logger.info("###########开始获取root topic备注信息###########");
            }
        }
    }

    /***
     * &Desc: 解析XMind: 用例节点的相关信息，并组装成一条测试用例，放入 MS测试用例对象 中
     * @param testCaseTopicNode 测试用例节点
     * @param markerIcon 测试用例节点的Marker标识值
     */
    public static TestMeterSphereCasePo dealXMindTestMeterSphereCase(Element testCaseTopicNode, String markerIcon){
        TestMeterSphereCasePo testCasePO = new TestMeterSphereCasePo();
        /** 取得：用例目录 */
        StringBuilder testCaseCatalog = new StringBuilder();
        Element prevTopicNode = testCaseTopicNode.getParent().getParent().getParent();
        // 回溯路径找到Test Case目录
        while(!prevTopicNode.getParent().getName().equals("sheet")){
            String catalogItem = prevTopicNode.element("title").getStringValue();
            if(testCaseCatalog.toString().equals("")){
                testCaseCatalog.append(catalogItem);
            }else {
                testCaseCatalog.insert(0, "/")
                        .insert(0,catalogItem);
            }
            prevTopicNode = prevTopicNode.getParent().getParent().getParent();
        }

        /** 取得：用例名称 */
        String testCaseName = testCaseTopicNode.element("title").getStringValue();

        /** 取得：前置条件 */
        String predication = "";
        Element notes = testCaseTopicNode.element("notes");
        if(notes != null){
            predication = notes.element("plain").getStringValue();
        }

        /** 取得：优先级数字 */
        String suffix = markerIcon.replaceAll("priority-", "");
        String priority = "";
        // 判断用例优先级
        switch (suffix) {
            case "1":
                priority = "P0";
                break;
            case "2":
                priority = "P1";
                break;
            case "3":
                priority = "P2";
                break;
            case "4":
                priority = "P3";
                break;
            default:
                priority = "P3";
                break;
        }

        /** 取得：步骤、期望 */
        List<String> steps = new ArrayList<>();
        List<String> results = new ArrayList<>();
        Element stepChildrenNode = testCaseTopicNode.element("children");
        // 获取用例的所有步骤
        try {
            if(stepChildrenNode != null){
                List<Element> stepTopicNodes = stepChildrenNode.element("topics").elements("topic");
                for (Element e: stepTopicNodes) {
                    // XMind copy节点无title节点问题，容错处理
                    Element step = e.element("title");
                    if(step != null){
                        steps.add(step.getStringValue());
                    }else {
                        steps.add("");
                    }
                    Element resultChildrenNode = e.element("children");
                    // 获取单个步骤的所有期望
                    if(resultChildrenNode != null){
                        List<Element> resultTopicNodes = resultChildrenNode.element("topics").elements("topic");
                        for (Element ee: resultTopicNodes) {
                            // XMind copy节点无title节点问题，容错处理
                            Element expect = ee.element("title");
                            if(expect != null){
                                results.add(expect.getStringValue());
                            }else {
                                results.add("");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("******解析测试用例步骤和期望出错：" + testCaseName);
            e.printStackTrace();
        }

        /** 赋值用例对象 */
        testCasePO.setTestCaseCatalog("/"+testCaseCatalog.toString());
        testCasePO.setTestCaseName(testCaseName);
        testCasePO.setPredication(predication);
        testCasePO.setDetails("");
        testCasePO.setActions(steps);
        testCasePO.setResults(results);
        testCasePO.setPriority(priority);
        testCasePO.setTestCaseType("功能测试");
        testCasePO.setUpdateModels("");
        testCasePO.setCaseStatus("Prepare");
        testCasePO.setCaseUsers("");
        logger.info("=====================>解析测试用例： " + testCaseName);
        return testCasePO;
    }

    /***
     * 代码新增部分：
     * &Desc: 解析XMind: 用例节点的相关信息，并组装成一条测试用例，放入 ONES测试用例对象 中
     * @param testCaseTopicNode 测试用例节点
     * @param markerIcon 测试用例节点的Marker标识值
     */
    public static TestOnesCasePo dealXMindTestOnesCase(Element testCaseTopicNode, String markerIcon){
        TestOnesCasePo testOnesCasePo = new TestOnesCasePo();

        /** 取得：用例目录 */
        StringBuilder testCaseCatalog = new StringBuilder();
        Element prevTopicNode = testCaseTopicNode.getParent().getParent().getParent();
        // 回溯路径找到Test Case目录
        while(!prevTopicNode.getParent().getName().equals("sheet")){
            String catalogItem = prevTopicNode.element("title").getStringValue();
            if(testCaseCatalog.toString().equals("")){
                testCaseCatalog.append(catalogItem);
            }else {
                testCaseCatalog.insert(0, "/")
                        .insert(0,catalogItem);
            }
            prevTopicNode = prevTopicNode.getParent().getParent().getParent();
        }

        /** 取得：用例名称 */
        String testCaseName = testCaseTopicNode.element("title").getStringValue();

        /** 取得：前置条件 */
        String predication = "";
        Element notes = testCaseTopicNode.element("notes");
        if(notes != null){
            predication = notes.element("plain").getStringValue();
        }

        /** 取得：优先级数字 */
        String suffix = markerIcon.replaceAll("priority-", "");
        String priority = "";
        // 判断用例优先级
        switch (suffix) {
            case "1":
                priority = "P0";
                break;
            case "2":
                priority = "P1";
                break;
            case "3":
                priority = "P2";
                break;
            case "4":
                priority = "P3";
                break;
            default:
                priority = "P4";
                break;
        }

        /** 取得：步骤、期望 */
        List<String> steps = new ArrayList<>();
        List<String> results = new ArrayList<>();
        Element stepChildrenNode = testCaseTopicNode.element("children");
        // 获取用例的所有步骤
        try {
            if(stepChildrenNode != null){
                List<Element> stepTopicNodes = stepChildrenNode.element("topics").elements("topic");
                for (Element e: stepTopicNodes) {
                    // XMind copy节点无title节点问题，容错处理
                    Element step = e.element("title");
                    if(step != null){
                        steps.add(step.getStringValue());
                    }else {
                        steps.add("");
                    }
                    Element resultChildrenNode = e.element("children");
                    // 获取单个步骤的所有期望
                    if(resultChildrenNode != null){
                        List<Element> resultTopicNodes = resultChildrenNode.element("topics").elements("topic");
                        for (Element ee: resultTopicNodes) {
                            // XMind copy节点无title节点问题，容错处理
                            Element expect = ee.element("title");
                            if(expect != null){
                                results.add(expect.getStringValue());
                            }else {
                                results.add("");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("******解析测试用例步骤和期望出错：" + testCaseName);
            e.printStackTrace();
        }
        /** 赋值用例对象 */
        //用例模块需要拆成6级模块testCaseCatalog
        String[] strList=testCaseCatalog.toString().split("/");
        try {
            testOnesCasePo.setTestCaseCatalog_1(String.valueOf(strList[0]));
            testOnesCasePo.setTestCaseCatalog_2(String.valueOf(strList[1]));
            testOnesCasePo.setTestCaseCatalog_3(String.valueOf(strList[2]));
            testOnesCasePo.setTestCaseCatalog_4(String.valueOf(strList[3]));
            testOnesCasePo.setTestCaseCatalog_5(String.valueOf(strList[4]));
            testOnesCasePo.setTestCaseCatalog_6(String.valueOf(strList[5]));
        } catch (IndexOutOfBoundsException e) {
            strList[0] = "";
            logger.info("=====================>数组长度不足，已自动创建并赋值");
        }
        logger.info("=====================>解析1级模块： "+testOnesCasePo.getTestCaseCatalog_1());
        logger.info("=====================>解析6级模块： "+testOnesCasePo.getTestCaseCatalog_6());
        testOnesCasePo.setTestCaseName(testCaseName);
        testOnesCasePo.setPredication(predication);
        testOnesCasePo.setCaseDetails("");
        testOnesCasePo.setActions(steps);
        testOnesCasePo.setResults(results);
        testOnesCasePo.setPriority(priority);
        testOnesCasePo.setTestCaseType("功能测试");
        testOnesCasePo.setCaseUsers("");
        logger.info("=====================>解析测试用例： " + testCaseName);
        return testOnesCasePo;
    }
}